package com.tianquan.lambda;/**
 * @author starsea
 * @date 2024-09-13 下午8:37
 */

import java.util.*;
import java.util.function.Function;

/**
 *@BelongsProject: hitch
 *@BelongsPackage: com.heima.modules.po
 *@Author: tianquan
 *@CreateTime: 2024-09-13  20:37
 *@Description: 测试
 *@Version: 1.0
 */


public class test {

    public static void main(String[] args) {
        User user = new User("tian",18,"男");
        User user1 = new User("tian1",13,"男");
        User user2 = new User("tian2",185,"女");
        User user3 = new User("tian3",168,"女");

        ArrayList<User> list = new ArrayList<>(4);
        list.add(user);
        list.add(user1);
        list.add(user2);
        list.add(user3);

        // 创建方式
        // Optional<OrderPO> optional = Optional.of(null);             // 传入的参数不能为null
        Optional<List<User>> optional1 = Optional.ofNullable(list);       // 传入的参数可以为null
        Optional<List<User>> optional2 = Optional.empty();                   // 创建一个空的Optional

        System.out.println("------------------------------------------------");

        // 判断是否为空
        System.out.println(optional1.isPresent());
        System.out.println(optional2.isPresent());

        System.out.println("------------------------------------------------");

        // 对属性操作            // 如果不为空，则执行ifPresent中的方法
        optional1.ifPresent(list1 -> list1.sort(Comparator.comparingInt(User::getAge)));
        optional1.ifPresent(list1 -> list1.forEach(System.out::println));

        System.out.println("------------------------------------------------");

        // 收集操作
        User o = optional1.flatMap((Function<List<User>, Optional<User>>) users -> {
            for (User user4 : users) {
                if (user4.getName().equals("tian10")) {
                    return Optional.of(user4);
                }
            }
            return Optional.empty();
        }).orElseThrow();
        System.out.println(o);


        System.out.println("------------------------------------------------");





    }
}
